const Storage = require('../../utils/storage')

Page({
  data: {
    keyword: '',
    showClear: false,
    searchHistory: [],
    hasSearched: false,
    activeTab: 'doctor',
    doctors: [],
    questions: [],
    articles: [],
    departmentId: '',
    diseaseId: ''
  },

  onLoad(options) {
    const { departmentId, diseaseId } = options;
    
    if (departmentId || diseaseId) {
      this.setData({
        departmentId: departmentId || '',
        diseaseId: diseaseId || '',
        hasSearched: true
      });
      
      this.searchWithParams();
    } else {
      this.loadSearchHistory();
    }
  },

  searchWithParams() {
    const { departmentId, diseaseId } = this.data;
    
    Promise.all([
      this.searchDoctors('', departmentId, diseaseId),
      this.searchQuestions('', departmentId, diseaseId),
      this.searchArticles('', departmentId, diseaseId)
    ]).then(([doctors, questions, articles]) => {
      this.setData({
        doctors,
        questions,
        articles
      });
    }).catch(err => {
      console.error('搜索失败：', err);
      this.useLocalData();
    });
  },

  onChange(e) {
    const value = e.detail.value;
    this.setData({
      keyword: value,
      showClear: !!value
    });
  },

  onClear() {
    this.setData({
      keyword: '',
      showClear: false,
      hasSearched: false,
      doctors: [],
      questions: [],
      articles: []
    }, () => {
      this.loadSearchHistory();
    });
  },

  searchDoctors(keyword, departmentId = '', diseaseId = '') {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://your-api-domain/api/v1/doctors/search',
        method: 'GET',
        data: {
          keyword,
          departmentId,
          diseaseId,
          page: 1,
          pageSize: 10
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        },
        fail: reject
      });
    });
  },

  searchQuestions(keyword, departmentId = '', diseaseId = '') {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://your-api-domain/api/v1/questions/search',
        method: 'GET',
        data: {
          keyword,
          departmentId,
          diseaseId,
          page: 1,
          pageSize: 10
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        },
        fail: reject
      });
    });
  },

  searchArticles(keyword, departmentId = '', diseaseId = '') {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://your-api-domain/api/v1/articles/search',
        method: 'GET',
        data: {
          keyword,
          departmentId,
          diseaseId,
          page: 1,
          pageSize: 10
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 0) {
            resolve(res.data.data);
          } else {
            reject(new Error(res.data.message || '请求失败'));
          }
        },
        fail: reject
      });
    });
  },

  onSearch() {
    const { keyword, departmentId, diseaseId } = this.data;
    if (!keyword.trim() && !departmentId && !diseaseId) return;
    
    this.setData({ hasSearched: true });
    this.saveSearchHistory(keyword);
    
    Promise.all([
      this.searchDoctors(keyword, departmentId, diseaseId),
      this.searchQuestions(keyword, departmentId, diseaseId),
      this.searchArticles(keyword, departmentId, diseaseId)
    ]).then(([doctors, questions, articles]) => {
      this.setData({
        doctors,
        questions,
        articles
      });
    }).catch(err => {
      console.error('搜索失败：', err);
      this.useLocalData();
    });
  },

  onHistoryTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword: keyword,
      hasSearched: true,
      showClear: true
    }, () => {
      this.onSearch();
    });
  },

  loadSearchHistory() {
    const cacheHistory = Storage.getSearchHistory();
    if (cacheHistory && cacheHistory.length > 0) {
      this.setData({ searchHistory: cacheHistory });
      return;
    }
    this.useDefaultHistory();
  },

  saveSearchHistory(keyword) {
    if (!keyword) return;
    
    let history = this.data.searchHistory;
    if (!history.includes(keyword)) {
      history.unshift(keyword);
      if (history.length > 10) {
        history = history.slice(0, 10);
      }
      this.setData({ searchHistory: history });
      Storage.setSearchHistory(history);
    }
  },

  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ searchHistory: [] });
          Storage.clearSearchHistory();
        }
      }
    });
  },

  useDefaultHistory() {
    const defaultHistory = ['头痛', '感冒', '发烧', '咳嗽', '失眠'];
    this.setData({ searchHistory: defaultHistory });
    Storage.setSearchHistory(defaultHistory);
  },

  useLocalData() {
    const keyword = this.data.keyword;
    this.setData({
      doctors: [
        {
          id: 1,
          name: '张医生',
          title: '主任医师',
          department: '内科-心血管科',
          hospital: '协和医院',
          hospitalLevel: '三甲',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
          skills: '冠心病、高血压、心律失常、心力衰竭等心血管疾病的诊断和治疗，在心血管疾病的预防和康复方面有丰富经验。',
          rating: 4.9,
          consultCount: '1.2万',
          price: '39'
        },
        {
          id: 2,
          name: '李医生',
          title: '副师',
          department: '神经内科',
          hospital: '华西医院',
          hospitalLevel: '三甲',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
          skills: '头痛、偏头痛、神经衰弱、脑血管疾病、记忆障碍、睡眠障碍等神经系统疾病的诊断和治疗。',
          rating: 4.8,
          consultCount: '8000',
          price: '29'
        },
        {
          id: 3,
          name: '王医生',
          title: '主治医师',
          department: '呼吸内科',
          hospital: '北京大学第一医院',
          hospitalLevel: '三甲',
          avatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
          skills: '支气管哮喘、慢性咳嗽、肺炎、慢性阻塞性肺疾病等呼吸系统疾病的诊断和治疗，对呼吸系统常见病和疑难病有丰富的临床经验。',
          rating: 4.7,
          consultCount: '5000',
          price: '19'
        }
      ],
      questions: [
        {
          id: 1,
          title: `${keyword}引起的头痛是什么原因？`,
          answers: [
            {
              id: 1,
              doctorName: '张医生',
              doctorTitle: '主任医师',
              doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
              content: '头痛可能有多种原因，需要具体分析。建议到医院进行详细检查，明确诊断后进行针对性治疗。',
              likeCount: 123,
              time: '2024-01-20'
            },
            {
              id: 2,
              doctorName: '李医生',
              doctorTitle: '副主任医师',
              doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
              content: '建议先做以下检查：1. 血压测量 2. 头部CT或核共振 3. 血常规等基础检查',
              likeCount: 89,
              time: '2024-01-19'
            }
          ]
        },
        {
          id: 2,
          title: `${keyword}会导致失眠吗？`,
          answers: [
            {
              id: 3,
              doctorName: '王医生',
              doctorTitle: '主任医师',
              doctorAvatar: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%8C%BB%E7%94%9F%E5%A4%B4%E5%83%8F.jpg',
              content: '失眠可能是由多种因素引起的，建议：1. 保持规律作息 2. 避免剧烈运动 3. 保持心情愉悦',
              likeCount: 156,
              time: '2024-01-18'
            }
          ]
        }
      ],
      articles: [
        {
          id: 1,
          name: '布洛芬缓释胶囊',
          specification: '0.3g*12粒/盒',
          indication: '用于缓解轻至中度疼痛，如头痛、关节痛、偏头痛、牙痛、肌肉痛、神经痛、痛经。也用于普通感冒或流行性感冒引起的发热。',
          type: 'OTC',
          price: '25.80',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%B8%83%E6%B4%9B%E8%8A%AC.png'
        },
        {
          id: 2,
          name: '阿莫西林胶囊',
          specification: '0.25g*20粒/盒',
          indication: '用于敏感菌所致的感染，如中耳炎、鼻窦炎、咽喉炎等。',
          type: '处方',
          price: '35.60',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 3,
          name: '感冒灵颗粒',
          specification: '10g*10袋/盒',
          indication: '用于感冒引起的头痛、发热、鼻塞、流涕、咽痛等症状。',
          type: 'OTC',
          price: '15.90',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%B8%83%E6%B4%9B%E8%8A%AC.png'
        },
        {
          id: 4,
          name: '盐酸二甲双胍片',
          specification: '0.5g*30片/',
          indication: '用于2型糖尿病，特别是单纯饮食控制及体育锻炼治疗无效的肥胖型2型糖尿病。',
          type: '处方',
          price: '28.50',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%B8%83%E6%B4%9B%E8%8A%AC.png'
        },
        {
          id: 5,
          name: '复方感冒灵片',
          specification: '12片*2板/盒',
          indication: '用于感冒引起的头痛、发热、鼻塞、流涕、咽痛等症状的治疗。',
          type: 'OTC',
          price: '22.80',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%B8%83%E6%B4%9B%E8%8A%AC.png'
        },
        {
          id: 6,
          name: '维生素C咀嚼片',
          specification: '100mg*60片/瓶',
          indication: '用于预防和治疗维生素C缺乏症，如坏血病。增强机体抵抗力。',
          type: 'OTC',
          price: '42.00',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E5%B8%83%E6%B4%9B%E8%8A%AC.png'
        },
        {
          id: 5,
          name: '盐酸左氧氟沙星片',
          specification: '0.1g*12片/盒',
          indication: '用于敏感菌所致的呼吸道、泌尿生殖道等感染性疾病的治疗。',
          type: '处方',
          price: '46.80',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 6,
          name: '复方甘草片',
          specification: '24片/盒',
          indication: '用于咽喉肿痛、咳嗽、咽干等症状的缓解。',
          type: 'OTC',
          price: '16.80',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 7,
          name: '盐酸雷尼替丁胶囊',
          specification: '0.15g*30粒/盒',
          indication: '用于胃溃疡、十二指肠溃疡、反流性食管炎等。',
          type: '处方',
          price: '28.90',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 8,
          name: '对乙酰氨基酚片',
          specification: '0.5g*12片/盒',
          indication: '用于感冒发热、头痛、牙痛、关节痛等症状的缓解。',
          type: 'OTC',
          price: '15.60',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 9,
          name: '枸橼酸西地那非片',
          specification: '50mg*2片/盒',
          indication: '用于勃起功能障碍的治疗。',
          type: '处方',
          price: '98.00',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 10,
          name: '盐酸氟桂利嗪胶囊',
          specification: '5mg*20粒/盒',
          indication: '用于偏头痛及血管神经性头痛的预防和治疗。',
          type: '处方',
          price: '35.60',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 11,
          name: '复方板蓝根颗粒',
          specification: '10g*20袋/盒',
          indication: '清热解毒，凉血利咽。用于上呼吸道感染等。',
          type: 'OTC',
          price: '32.80',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 12,
          name: '盐酸小布洛诺片',
          specification: '5mg*20片/盒',
          indication: '用于各种原因引起的中、重度疼痛。',
          type: '处方',
          price: '58.00',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 13,
          name: '复方草珊瑚含片',
          specification: '0.6g*24片/盒',
          indication: '用于咽喉肿痛、口腔溃疡等症状。',
          type: 'OTC',
          price: '24.50',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        },
        {
          id: 14,
          name: '盐酸特比萘芬片',
          specification: '0.25g*14片/盒',
          indication: '用于真菌引起的皮肤和指（趾）甲感染。',
          type: '处方',
          price: '75.60',
          image: 'https://inquiry-xcx.oss-cn-beijing.aliyuncs.com/%E9%98%BF%E8%8E%AB%E8%A5%BF%E6%9E%97.jpeg'
        }
      ]
    });
  },

  onDoctorTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/doctor/detail?id=${id}`
    });
  },

  onQuestionTap(e) {
    const questionId = e.currentTarget.dataset.id;
    console.log('Navigating to QnA page with ID:', questionId);
    wx.navigateTo({
      url: `/pages/qna/index?id=${questionId}`
    });
  },

  onArticleTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/article/detail?id=${id}`
    });
  },

  onTabChange(e) {
    this.setData({
      activeTab: e.detail.value
    });
  },

  navigateToQnA(e) {
    const questionId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/qna/index?id=${questionId}`
    });
  },

  onMedicineTap(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/medicine/detail?id=${id}`
    });
  }
}); 